package com.wkbb.sports.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.utils.StringUtil;
import com.wkbb.sports.feign.BasicFeignService;
import com.wkbb.sports.mapper.HlifeBannerMapper;
import com.wkbb.sports.mapper.MetaverseActivityMapper;
import com.wkbb.sports.mapper.StudentArenaMapper;
import com.wkbb.sports.model.*;
import com.wkbb.sports.service.StudentArenaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class StudentArenaServiceImpl extends BaseServiceImpl<StudentArena> implements StudentArenaService {

    @Autowired
    private BasicFeignService basicFeignService;
    @Autowired
    private StudentArenaMapper studentArenaMapper;

    @Autowired
    public void setMapper(StudentArenaMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    @Transactional(readOnly=true)
    public List<StudentArenaTeam> getTeamListByPage(Map<String, Object> params) throws Exception {
//        Page<StudentArenaTeam> page = PageHelper.startPage(pageNo, pageSize,true);
//        PageInfo<StudentArenaTeam> pageInfo = new PageInfo<>(studentArenaMapper.findTeamList(params));
//        pageInfo.setTotal(page.getTotal());
//        return pageInfo;
        return studentArenaMapper.findTeamList(params);
    }

    @Override
    @Transactional(readOnly = true)
    public ResultDTO<List<StudentArenaTrain>> getTeamStuList(Map<String, Object> params) throws Exception {
        StudentArena studentArena = studentArenaMapper.getByPrimaryKey((Long) params.get("arenaId"));
        if (studentArena == null){
            return ResultDTO.errorResult("错误!不存在的擂台");
        }
        //个人赛
        if (studentArena.getType() == 1){
            return ResultDTO.errorResult("错误!不存在的擂台团队");
        }
//        params.put("statisticalType",studentArena.getStatisticalType());
        List<StudentArenaTrain> list = studentArenaMapper.getTeamStuList(params);
        return ResultDTO.successResult(list);
    }

    @Override
    @Transactional(readOnly = true)
    public ResultDTO<PageInfo<StudentArenaTrain>> getStuListByPage(Long arenaId, int pageNo, int pageSize) throws Exception {
        StudentArena studentArena = studentArenaMapper.getByPrimaryKey(arenaId);
        if (studentArena == null){
            return ResultDTO.errorResult("错误!不存在的擂台");
        }
        //个人赛
        if (studentArena.getType() == 2){
            return ResultDTO.errorResult("错误!不是个人擂台");
        }
        Page<StudentArenaTrain> page = PageHelper.startPage(pageNo, pageSize,true);
        PageInfo<StudentArenaTrain> pageInfo = new PageInfo<>(studentArenaMapper.getStuList(arenaId));
        pageInfo.setTotal(page.getTotal());
        return ResultDTO.successResult(page);
    }

    @Override
    public boolean arenaChange(StudentArena info) throws Exception {
        StudentArena championInfo = info.getType() == 1? studentArenaMapper.getChampionInfoType1(info) : studentArenaMapper.getChampionInfoType2(info);
        if (championInfo != null){
            info.setChampionName(championInfo.getChampionName());
            info.setChampionAchievement(championInfo.getChampionAchievement());
            info.setPlayerCount(championInfo.getPlayerCount());
            studentArenaMapper.update(info);
            return true;
        }
        return false;
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<StudentArena> getMyListByPage(Map<String, Object> params, int pageNo, int pageSize) {
        Page<StudentArena> page = PageHelper.startPage(pageNo, pageSize,true);
        List<StudentArena> list = studentArenaMapper.getMyListByPage(params);
        for (StudentArena item:list){
            item.setInviteCode(null);
        }
        PageInfo<StudentArena> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    @Override
    public ResultDTO<Boolean> validInviteCode(Long arenaId, Long studentId, String inviteCode) {
        StudentArena studentArena = studentArenaMapper.getByPrimaryKey(arenaId);
        if (studentArena == null){
            return ResultDTO.errorResult("错误!不存在的擂台");
        }
        if (studentArena.getGenerateInviteCode()){
            if (!studentArena.getStudentId().equals(studentId) && !studentArena.getInviteCode().equals(inviteCode)){
                return ResultDTO.errorResult("邀请码错误，请重新输入！");
            }
        }
        return ResultDTO.successResult(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOfficialArena(StudentArena studentArena)throws Exception {
        studentArena.setName(studentArena.getName().trim());
        studentArenaMapper.insert(studentArena);
//        HlifeBanner banner = new HlifeBanner();
//        banner.setLogo(studentArena.getLogo());
//        banner.setName(studentArena.getName());
//        banner.setArenaId(studentArena.getId());
//        banner.setTerminal(4);
//        bannerMapper.insert(banner);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<StudentArenaTeam> insertTeam(StudentArenaTeam info) throws Exception {
        StudentArena studentArena = studentArenaMapper.getByPrimaryKey(info.getArenaId());
        if (studentArena == null){
            return ResultDTO.errorResult("错误!不存在的擂台");
        }
        if (studentArena.getGenerateInviteCode()){
            if (!studentArena.getStudentId().equals(info.getStudentId()) && !studentArena.getInviteCode().equals(info.getInviteCode())){
                return ResultDTO.errorResult("邀请码错误，请重新输入！");
            }
        }
        //个人赛
        if (studentArena.getType() == 1){
            return ResultDTO.errorResult("个人赛擂台，无法添加团队");
        }
        if (studentArena.getState() == 2){
            return ResultDTO.errorResult("错误!擂台赛已经结束");
        }
        //团队数量限制。判断是否可以添加
        int remainder = 1;
        if (studentArena.getChallengeTeamNum() > 0){
            remainder = studentArena.getChallengeTeamNum() - studentArenaMapper.getTeamCount(info.getArenaId());
        }
        if (remainder <= 0){
            return ResultDTO.errorResult("该擂台赛已达最大报名限制");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("arenaId",info.getArenaId());
        params.put("teamName",info.getTeamName());
        StudentArenaTeam team = studentArenaMapper.findTeam(params);
        if (team != null){
            return ResultDTO.errorResult("该团队已存在，请勿重复操作");
        }
        params.put("studentId",info.getStudentId());
        List<StudentArenaTeamStu> stuList = studentArenaMapper.findTeamStuList(params);
        if (stuList.size() > 0){
            return ResultDTO.errorResult("该学生已经加入了擂台团队，请勿重复操作");
        }
        studentArenaMapper.insertTeam(info);
        StudentArenaTeamStu stu = new StudentArenaTeamStu();
        stu.setArenaId(info.getArenaId());
        stu.setArenaTeamId(info.getId());
        stu.setStudentId(info.getStudentId());
        return insertTeamStu(studentArena,stu);
    }

    public ResultDTO<StudentArenaTeam> insertTeamStu(StudentArena studentArena,StudentArenaTeamStu info) throws Exception{
        ResultDTO<StudentInfoDto> res = basicFeignService.getStudentByStudentNo(null,null,info.getStudentId(),null);
        if (res.isSuccess()){
            StudentInfoDto studentInfoDto = res.getData();
            info.setStudentName(studentInfoDto.getName());
            info.setHeadImgUrl(studentInfoDto.getHeadImgUrl());
            info.setUserType(studentInfoDto.getUserType());
            studentArenaMapper.insertTeamStu(info);
            arenaChange(studentArena);
            return ResultDTO.successResult();
        }
        return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<StudentArenaTeamStu> delArenaTeamStu(Long arenaTeamId, Long captainStudentId, Long studentId) throws Exception{
        Map<String, Object> params = new HashMap<>();
        params.put("id",arenaTeamId);
        StudentArenaTeam team = studentArenaMapper.findTeam(params);
        if (team == null){
            return ResultDTO.errorResult("错误!不存在的团队");
        }
        if (!captainStudentId.equals(team.getStudentId())){
            return ResultDTO.errorResult("没有权限!不是团队创建者");
        }
        params.put("studentId",studentId);
        params.put("arenaTeamId",arenaTeamId);
        List<StudentArenaTeamStu> stuList = studentArenaMapper.findTeamStuList(params);
        if (stuList.size() == 0){
            return ResultDTO.errorResult("该学生已被移出当前团队");
        }
        //移出团队
        studentArenaMapper.delArenaTeamStu(params);
        StudentArena studentArena = studentArenaMapper.getByPrimaryKey(team.getArenaId());
        if (studentArena == null){
            return ResultDTO.errorResult("错误!不存在的擂台");
        }
        params.put("arenaId",team.getArenaId());
        //清除成绩
        studentArenaMapper.delArenaTrain(params);
        //更新团队成绩
        StudentArenaTeam arenaTeam = studentArenaMapper.getTeamStatistical(params);
        if (arenaTeam.getTotalAchievement() == null) arenaTeam.setTotalAchievement(0.0);
        if (arenaTeam.getTotalTime() == null) arenaTeam.setTotalTime(0);
        studentArenaMapper.updateTeam(arenaTeam);
        arenaChange(studentArena);
        return new ResultDTO<>();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO joinArenaTeam(StudentArenaTeamStu info) throws Exception {
        StudentArena studentArena = studentArenaMapper.getByPrimaryKey(info.getArenaId());
        if (studentArena == null){
            return ResultDTO.errorResult("错误!不存在的擂台");
        }
        if (info.getCaptainStudentId() == null){
            if (studentArena.getGenerateInviteCode()){
                if (!studentArena.getStudentId().equals(info.getStudentId()) && !studentArena.getInviteCode().equals(info.getInviteCode())){
                    return ResultDTO.errorResult("邀请码错误，请重新输入！");
                }
            }
        }
        Map<String, Object> params = new HashMap<>();
        params.put("id",info.getArenaTeamId());
        StudentArenaTeam team = studentArenaMapper.findTeam(params);
        if (team == null){
            return ResultDTO.errorResult("错误!无法加入不存在的团队");
        }
        if (info.getCaptainStudentId() != null && !team.getStudentId().equals(info.getCaptainStudentId())){
            return ResultDTO.errorResult("错误!无法加入不存在的团队");
        }
        if (team.getChallengeNum() > 0){
            //战队
            int remainder = team.getChallengeNum() - team.getTeamNum();
            if (remainder <= 0){
                return ResultDTO.errorResult("错误!擂台团队已达最大人数限制");
            }
        }
        params.put("arenaId",info.getArenaId());
        params.put("studentId",info.getStudentId());
        List<StudentArenaTeamStu> stuList = studentArenaMapper.findTeamStuList(params);
        if (stuList.size() > 0){
            return ResultDTO.errorResult("该用户已经加入了擂台团队，请勿重复操作");
        }
        //团队人数+1
        studentArenaMapper.addTeamNum(info.getArenaTeamId());
        return insertTeamStu(studentArena,info);
    }

    @Override
    public ResultDTO<StudentArenaTeam> isFamilyArenaChange(Long arenaId, Long studentId, Long userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("arenaId",arenaId);
        params.put("userId",userId);
        StudentArenaTeam team = studentArenaMapper.findTeam(params);
        if (team == null){
            params.put("studentId",studentId);
            params.remove("userId");
            team = studentArenaMapper.findTeam(params);
        }
        if (team == null){
            return ResultDTO.errorResult("暂未创建亲子团队");
        }
        params.put("studentId",studentId);
        List<StudentArenaTeamStu> stuList = studentArenaMapper.findTeamStuList(params);
        team.setCanChallenge(true);
        if (stuList.size() == 0){
            if (team.getChallengeNum() > 0){
                //战队
                int remainder = team.getChallengeNum() - team.getTeamNum();
                if (remainder <= 0){
                    team.setCanChallenge(false);
                }
            }
        }
        return new ResultDTO<>(team);
    }

    @Override
    @Transactional(readOnly = true)
    public List<StudentArenaTrain> getStuChallengeList(Map<String, Object> params) {
        return studentArenaMapper.getStuChallengeList(params);
    }

    @Override
    @Transactional(readOnly = true)
    public StudentArenaTrain getStuTrain(Long arenaId, Long studentId) {
        return studentArenaMapper.getStuTrain(arenaId,studentId);
    }


}
